import { ElSubMenu, ElMenuItem } from 'element-plus'
import { useRenderMenuTitle } from './useRenderMenuTitle'
import { RouteMeta } from 'vue-router'
const { renderMenuTitle } = useRenderMenuTitle()

type MenuBody = {
  name: string
  children: MenuBody[] | null
  meta: RouteMeta
}
const menuCache = {}
export const getRouteParams = (name: string) => {
  return menuCache[name]
}
const formatMenu = (menu: AppRouteRecordRaw): MenuBody | null => {
  if (menu.meta != null && menu.meta.hidden) {
    return null
  } else if (menu.children != null && menu.children.length > 0) {
    const child: MenuBody[] = []
    menu.children.forEach((c) => {
      const res = formatMenu(c)
      if (res != null) {
        child.push(res)
      }
    })
    if (child.length == 1 && menu.meta && !menu.meta.alwaysShow) {
      return child[0]
    } else if (child.length > 0) {
      menuCache[menu.name] = menu.meta?.params
      return {
        name: menu.name,
        meta: menu.meta ?? {},
        children: child
      }
    }
    if (menu.meta == null || !menu.meta.alwaysShow) {
      return null
    }
  }
  menuCache[menu.name] = menu.meta?.params
  return {
    name: menu.name,
    meta: menu.meta ?? {},
    children: null
  }
}
const renderItem = (menus: MenuBody[] | null) => {
  if (menus == null) {
    return null
  }
  return menus.map((v) => {
    if (v.children == null) {
      return <ElMenuItem index={v.name}>{{ default: () => renderMenuTitle(v.meta) }}</ElMenuItem>
    } else {
      return (
        <ElSubMenu index={v.name}>
          {{ title: () => renderMenuTitle(v.meta), default: () => renderItem(v.children) }}
        </ElSubMenu>
      )
    }
  })
}
export const useRenderMenuItem = () => {
  const renderMenuItem = (routers: AppRouteRecordRaw[]) => {
    const list: MenuBody[] = []
    routers.forEach((c) => {
      const menu = formatMenu(c)
      if (menu != null) {
        list.push(menu)
      }
    })
    return renderItem(list)
  }
  return {
    renderMenuItem
  }
}
